package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.collection.CollUtil;
import com.zmj.sy.mom.srv.aps.bean.entity.order.OrderBom;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.qms.OrderCheckPhaseGenerateFromBomReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.qms.PartSyncReqVo;
import com.zmj.sy.mom.srv.aps.feign.QmsApiClient;
import com.zmj.sy.mom.srv.aps.mapper.OrderBomMapper;
import com.zmj.sy.mom.srv.aps.utils.SySecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class QmsService {

    private final OrderBomMapper orderBomMapper;

    private final QmsApiClient qmsApiClient;

    public void pushOrderMaterial2QMS(Integer bomId) {
        OrderBom root = orderBomMapper.lambdaQuery()
                .eq(OrderBom::getId, bomId)
                .one();
        Map<Integer, List<OrderBom>> orderBomTree = orderBomMapper.lambdaQuery()
                .eq(OrderBom::getOrderId, root.getOrderId())
                .list()
                .stream()
                .collect(Collectors.groupingBy(bom -> bom.getPid() == null ? 0 : bom.getPid()));
        List<OrderBom> bomList = new ArrayList<>();
        Stack<OrderBom> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            OrderBom bom = stack.pop();
            bomList.add(bom);
            List<OrderBom> children = orderBomTree.get(bom.getId());
            if (CollUtil.isNotEmpty(children)) {
                stack.addAll(children);
            }
        }
        List<PartSyncReqVo> req = bomList.stream()
                .map(bom -> {
                    PartSyncReqVo item = new PartSyncReqVo();
                    item.setDrawing(bom.getMaterCode());
                    item.setMaterialCode(bom.getErpCode());
                    item.setMaterialName(bom.getMaterName());
                    item.setMaterialType(bom.getMaterType());
                    item.setPlmId(bom.getPlmId());
                    return item;
                })
                .collect(Collectors.toList());
        BaseResVo baseResVo = qmsApiClient.syncPart(req);
        if (baseResVo.getCode() != 0) {
            log.info("推送物料信息到QMS失败：{}", baseResVo.getMessage());
        }

        OrderCheckPhaseGenerateFromBomReqVo reqVo = new OrderCheckPhaseGenerateFromBomReqVo();
        reqVo.setId("2$" + root.getOrderId());
        String userCode = SySecurityUtils.getUserCode();
        reqVo.setCreateUserName(userCode);
        BaseResVo generate = qmsApiClient.generateJson(reqVo);
        if (generate.getCode() != 0) {
            log.info("生成检验模板失败：{}", generate.getMessage());
        }
    }



}
